<template>
  <div class="main-container">
    <a-tag checkable color="arcoblue" style="width: 100%; height: 40px"
      >提交/回复工单时，请仔细描述，以便我们更快的处理工单，感谢您对我们工作的支持</a-tag
    >
    <div class="detailContent">
      <div class="topBox">
        <div class="leftBox">
          <img class="avatarImg" src="@/assets/real.png" alt="" />
        </div>
        <div class="rightBox">
          <div class="name_time">
            <p class="names">{{ orderInfo.handlerList.system.systemName }}</p>
            <p class="times">{{ orderInfo.handlerList.addTime }}</p>
          </div>
          <div class="titles">{{ orderInfo.handlerList.title }}</div>
          <div class="contents" v-html="orderInfo.handlerList.content"></div>
        </div>
      </div>
      <div class="endBox">
        <div
          class="topBoxs"
          v-for="(item, index) in orderInfo.handlerList.workOrderHandlerList"
          :key="index"
        >
          <div class="leftBox">
            <img
              class="avatarImg"
              v-if="item.controlOrSystem == true"
              src="@/assets/real.png"
              alt=""
            />
            <img class="avatarImg" v-else src="@/assets/icon.jpg" alt="" />
          </div>
          <div class="rightBox">
            <div class="name_time">
              <p class="names" v-if="item.controlOrSystem == true">{{
                orderInfo.handlerList.system.systemName
              }}</p>
              <p class="names_" v-else>{{ item.handlerUserName }}</p>
              <p class="times">{{ item.addTime }}</p>
            </div>
            <div class="contents" v-html="item.content"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="bottomBox">
      <a-button type="primary" @click="subHuifu">回复工单</a-button>
    </div>
    <!-- 处理工单 -->
    <a-modal
      v-model:visible="chuliVisible"
      @before-close="handleCancel"
      width="800px"
      title="回复工单"
      :mask-closable="false"
      title-align="start"
      :body-style="{}"
    >
      <a-form
        style="margin-top: 10px"
        ref="userForm"
        :auto-label-width="true"
        :model="orderInfo.subForm"
      >
        <a-form-item
          hide-label
          field="content"
          :rules="[{ required: true, message: '请输入回复内容' }]"
          style="width: 100%"
        >
          <div style="border: 1px solid #ccc">
            <Toolbar
              :editor="editorRef"
              style="border-bottom: 1px solid #ccc"
              :default-config="toolbarConfig"
            />
            <Editor
              v-model="orderInfo.subForm.content"
              :default-config="editorConfig"
              class="editor_custom"
              style="height: 332px; overflow-y: hidden"
              @on-created="handleCreated"
              @on-change="handleChange"
              @on-destroyed="handleDestroyed"
              @on-focus="handleFocus"
              @on-blur="handleBlur"
              @custom-alert="customAlert"
              @custom-paste="customPaste"
            />
          </div>
        </a-form-item>
      </a-form>

      <template #footer>
        <a-space>
          <a-button @click="handleHuifu">仅回复</a-button>
          <a-button type="primary" @click="handleBeforeOk">回复并完结</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { get, post, formpost } from '@/api/http'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { useRoute, useRouter } from 'vue-router'
  import { getHandlerInfo, HandlerInfo, overWorkOrder, addWorkOrder } from '@/api/url.ts'
  import { onMounted, reactive, ref, onBeforeUnmount, shallowRef, computed } from 'vue'
  const router = useRouter()
  const route = useRoute()
  const props = defineProps({
    modelValue: {
      type: String,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  })
  const chuliVisible = ref(false)
  const orderInfo: any = reactive({
    info: {
      systemVersion: {},
      system: {},
    },
    showType: false,
    addOrderVisible: false,
    handlerList: {
      system: {},
      workOrderHandlerList: [],
    },
    templatesList: [],
    templatesForm: {
      title: '',
      typeId: '',
      content: '',
    },
    activeKey: null,
    subForm: { content: '', id: '' },
  })
  const userForm = ref<typeof Form>()
  const handleCancel = () => {
    userForm.value?.resetFields()
    chuliVisible.value = false
  }
  const subHuifu = () => {
    chuliVisible.value = true
  }
  const handleHuifu = () => {
    orderInfo.subForm.id = route.query.id

    post({
      url: HandlerInfo,
      data: () => {
        return {
          ...orderInfo.subForm,
        }
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        handleCancel()
        chuliDetails()
      }
    })
  }
  const handleBeforeOk = () => {
    orderInfo.subForm.id = route.query.id

    post({
      url: overWorkOrder,
      data: () => {
        return {
          ...orderInfo.subForm,
        }
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        handleCancel()
        chuliDetails()
      }
    })
  }
  const chuliDetails = (val: any) => {
    get({
      url: getHandlerInfo,
      data: () => {
        return {
          id: route.query.id,
        }
      },
    }).then((res) => {
      orderInfo.handlerList = res.data
      orderInfo.subForm.id = res.data.id
      orderInfo.activeKey = orderInfo.handlerList.workOrderHandlerList.length - 1
    })
    orderInfo.info = val
  }
  onMounted(() => {
    chuliDetails()
  })
  const headerObj = ref({})
  const AuthorizationHeader = () => {
    // if (tokenStore.token != '') {
    //     if (tokenStore.token != '0') {
    //         headerObj.value.Authorization =  tokenStore.token
    //     } else {
    //         headerObj.value.Authorization = userOutsideStore.tokenHead + userOutsideStore.token
    //     }
    // }
  }
  // 编辑器实例，必须用 shallowRef，重要！
  const editorRef = shallowRef()
  const editorRef1 = shallowRef()
  const toolbarConfig = {
    excludeKeys: ['group-video', 'insertImage', 'insertLink', 'emotion'], // 此处不需要的工具栏选项
  }

  const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {},
    hoverbarKeys: {
      image: {
        // 清空 image 元素的 hoverbar
        menuKeys: [],
      },
    },
  }

  // 上传图片
  editorConfig.MENU_CONF['uploadImage'] = {
    // 上传图片的接口地址
    server: '/app/file/upload',
    // form-data fieldName ，默认值 'wangeditor-uploaded-image'
    fieldName: 'file',

    // 单个文件的最大体积限制，默认为 2M
    maxFileSize: 5 * 1024 * 1024, // 5M

    // 最多可上传几个文件，默认为 100
    maxNumberOfFiles: 20,

    // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
    allowedFileTypes: ['image/png,image/jpeg,image/jpg'],

    // 小于该值就插入 base64 格式（而不上传），默认为 0
    base64LimitSize: 0, // 5kb
    // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
    // meta: {
    //     token: 'xxx',
    //     otherKey: 'yyy'
    // },

    // 将 meta 拼接到 url 参数中，默认 false
    metaWithUrl: false,

    // 自定义增加 http  header
    headers: headerObj,

    // 跨域是否传递 cookie ，默认为 false
    withCredentials: true,

    // 超时时间，默认为 10 秒
    timeout: 5 * 1000, // 5 秒
    // 上传之前触发
    onBeforeUpload(file: { [s: string]: unknown } | ArrayLike<unknown>) {
      // file 选中的文件，格式如 { key: file }
      let fileObj = Object.values(file)[0].data
      const isJPG =
        fileObj.type == 'image/jpg' || fileObj.type == 'image/jpeg' || fileObj.type == 'image/png'
      if (!isJPG) {
        Message.error('图片只能是 JPG、GIF、PNG 格式!')
      }
      // 判断图片宽高
      // 定义 filereader对象

      // 判断图片大小
      let isLt = fileObj.size / 1024 / 1024 < 5 // 判断是否小于5M
      if (!isLt) {
        Message.error('图片大小不能超过5M! 请重新上传')
      }
      if (!isJPG) {
        return false
      } else if (!isLt) {
        return false
      } else {
        return file
      }
      // 可以 return
      // 1. return file 或者 new 一个 file ，接下来将上传
      // 2. return false ，不上传这个 file
    },
    // 上传进度的回调函数
    onProgress(progress: any) {
      // progress 是 0-100 的数字
      console.log('progress', progress)
    },
    // 单个文件上传成功之后
    onSuccess(file: { name: any }, res: any) {
      console.log(`${file.name} 上传成功`, res)
    },
    // 自定义插入图片
    customInsert(
      res: { data: { path: string } },
      insertFn: (arg0: string, arg1: string, arg2: string) => void
    ) {
      console.log(window.location.host)
      // res 即服务端的返回结果
      // 从 res 中找到 url alt href ，然后插图图片
      insertFn('http://' + window.location.host + res.data.path, '', '')
    },
    // 单个文件上传失败
    // onFailed(file, res) {
    //     console.log(`${file.name} 上传失败`, res)
    // },
    // 上传错误，或者触发 timeout 超时
    onError(file: { name: any }, err: any, res: any) {
      console.log(`${file.name} 上传出错`, err, res)
    },
  }
  // 上传视频
  editorConfig.MENU_CONF['uploadVideo'] = {
    // 上传视频接口地址
    // server: usUploadStore().uploadVideo,
    // form-data fieldName ，默认值 'wangeditor-uploaded-video'
    fieldName: 'file',

    // 单个文件的最大体积限制，默认为 10M
    maxFileSize: 5 * 1024 * 1024, // 5M

    // 最多可上传几个文件，默认为 5
    maxNumberOfFiles: 3,

    // 选择文件时的类型限制，默认为 ['video/*'] 。如不想限制，则设置为 []
    allowedFileTypes: ['video/mp4'],

    // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
    // meta: {
    //     token: 'xxx',
    //     otherKey: 'yyy'
    // },

    // 将 meta 拼接到 url 参数中，默认 false
    metaWithUrl: false,

    // 自定义增加 http  header
    headers: headerObj,

    // 跨域是否传递 cookie ，默认为 false
    withCredentials: true,

    // 超时时间，默认为 30 秒
    timeout: 15 * 1000, // 15 秒

    // 视频不支持 base64 格式插入
    // 自定义插入视频
    customInsert(res: { data: { url: any } }, insertFn: (arg0: any) => void) {
      // res 即服务端的返回结果

      // 从 res 中找到 url ，然后插入视频
      insertFn(res.data.url)
    },
    // 上传之前触发
    onBeforeUpload(file: any) {
      // file 选中的文件，格式如 { key: file }
      return file

      // 可以 return
      // 1. return file 或者 new 一个 file ，接下来将上传
      // 2. return false ，不上传这个 file
    },
    // 上传进度的回调函数
    onProgress(progress: any) {
      // progress 是 0-100 的数字
      console.log('progress', progress)
    },
    // 单个文件上传成功之后
    onSuccess(file: { name: any }, res: any) {
      console.log(`${file.name} 上传成功`, res)
    },
    // 单个文件上传失败
    onFailed(file: { name: any }, res: any) {
      console.log(`${file.name} 上传失败`, res)
    },
    // 上传错误，或者触发 timeout 超时
    onError(file: { name: any }, err: any, res: any) {
      console.log(`${file.name} 上传出错`, err, res)
    },
  }
  // 组件销毁时，也及时销毁编辑器，重要！
  onBeforeUnmount(() => {
    const editor = editorRef.value
    const editor1 = editorRef1.value
    if (editor == null) return
    editor.destroy()
    if (editor1 == null) return
    editor1.destroy()
  })

  // 编辑器回调函数
  const handleCreated = (editor: { disable: () => void; enable: () => void }) => {
    editorRef.value = editor // 记录 editor 实例，重要！
    if (props.disabled) {
      editor.disable()
    } else {
      editor.enable()
    }
  }
  // 编辑器回调函数
  const handleCreated1 = (editor: { disable: () => void; enable: () => void }) => {
    editorRef1.value = editor // 记录 editor 实例，重要！
    if (props.disabled) {
      editor.disable()
    } else {
      editor.enable()
    }
  }
  const handleChange = (editor: any) => {
    return editor
  }
  const handleDestroyed = (editor: any) => {
    // console.log('destroyed', editor)
    return editor
  }
  const handleFocus = (editor: any) => {
    //console.log('focus', editor)
    return editor
  }
  const handleBlur = (editor: any) => {
    //console.log('blur', editor)
    return editor
  }
  const customAlert = (info: any, type: any) => {
    alert(`【自定义提示】${type} - ${info}`)
  }
  const customPaste = (editor: any, event: any, callback: (arg0: boolean) => void) => {
    console.log('ClipboardEvent 粘贴事件对象', event)

    // 自定义插入内容
    // editor.insertText('xxx')

    // 返回值（注意，vue 事件的返回值，不能用 return）
    // callback(false) // 返回 false ，阻止默认粘贴行为
    callback(true) // 返回 true ，继续默认的粘贴行为
  }
</script>

<style scoped lang="less">
  :deep(.arco-alert-info) {
    background-color: rgb(var(--arcoblue-2)) !important;
    color: #fff !important;
  }

  .bottomBox {
    width: calc(100% - 210px);
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--color-bg-1);
    position: fixed;
    bottom: 0px;
    right: 210px;
    left: 210px;
  }
  .detailContent {
    height: 70vh;
    overflow-y: scroll;
    padding: 20px;
    box-sizing: border-box;
    margin-top: 20px;
    border-radius: 10px;
    background-color: var(--color-bg-1);
    .endBox {
      margin-top: 40px;
      .topBoxs {
        width: 100%;
        margin-top: 16px;
        display: flex;
        align-items: flex-start;
        .leftBox {
          .avatarImg {
            width: 50px;
            height: 50px;
          }
        }
        .rightBox {
          margin-left: 10px;
          .name_time {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            .names {
              color: #4e5969;
              font-size: 16px;
              margin-right: 20px;
            }
            .names_ {
              color: #3491fa;
              font-size: 16px;
              margin-right: 20px;
            }
            .times {
              line-height: 16px;
              color: #a9aeb8;
              font-size: 12px;
            }
          }
          .titles {
            font-size: 14px;
            color: #1d2129;
            margin-bottom: 10px;
          }
        }
      }
    }
    .topBox {
      width: 100%;
      display: flex;
      align-items: flex-start;
      .leftBox {
        .avatarImg {
          width: 50px;
          height: 50px;
        }
      }
      .rightBox {
        margin-left: 10px;
        .name_time {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          .names {
            color: #4e5969;
            font-size: 16px;
            margin-right: 20px;
          }
          .names_ {
            color: #3491fa;
            font-size: 16px;
            margin-right: 20px;
          }
          .times {
            color: #a9aeb8;
            font-size: 12px;
          }
        }
        .titles {
          font-size: 14px;
          color: #1d2129;
          margin-bottom: 10px;
        }
      }
    }
  }
</style>
